package whf.framework.tools.generator.ui;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import whf.framework.config.ApplicationConfig;
import whf.framework.tools.generator.cfg.Config;
import whf.framework.util.StringUtils;

/**
 * <p>Title: 代码生成工具</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: whf</p>
 *
 * @author wanghaifeng
 * @version 1.0
 */
public class DataPanel extends JPanel {
	private final static String[] NODES = {"name", "parser", "sql", "driver", "url", "user", "password", 
		"default-db-name", "default-java-dir", "default-jsp-dir", "default-sub-module", "default-table-pre",
		"default-root-package"};
    private static String[][] DATABASE_TYPES = null;
    static{
    	String typestr = ApplicationConfig.getInstance().getValue("code-generator.types"); 
    	String[] types = StringUtils.split(typestr, ",");
    	DATABASE_TYPES = new String[types.length][NODES.length];
    	for(int i=0; i< types.length; i++){
    		for(int j=0; j < NODES.length; j++){
    			DATABASE_TYPES[i][j] = ApplicationConfig.getInstance().getValue("code-generator."+types[i]+"."+NODES[j]);
    		}
    	}
    }

    private BorderLayout borderLayout1 = new BorderLayout();
    private JPanel jPanel1 = new JPanel();
    private JLabel jLabel1 = new JLabel();
    private GridLayout gridLayout1 = new GridLayout();
    private JComboBox tableParser = new JComboBox();
    private JLabel jLabel2 = new JLabel();
    private JTextField description = new JTextField();
    private JPanel jPanel2 = new JPanel();
    private JPanel jPanel3 = new JPanel();
    private BorderLayout borderLayout2 = new BorderLayout();
    private GridLayout gridLayout2 = new GridLayout();
    private JLabel jLabel3 = new JLabel();
    private JTextField driver = new JTextField();
    private JLabel jLabel4 = new JLabel();
    private JTextField url = new JTextField();
    private JLabel jLabel5 = new JLabel();
    private JTextField username = new JTextField();
    private JLabel jLabel6 = new JLabel();
    private JPasswordField password = new JPasswordField();
    private JLabel jLabel7 = new JLabel();
    private JTextField schema = new JTextField();
    private JLabel jLabel8 = new JLabel();
    private JTextField tablePrefix = new JTextField();
    private JPanel jPanel4 = new JPanel();
    private JLabel jLabel9 = new JLabel();
    private JTextField submodule = new JTextField();
    private JButton jLabel10 = new JButton();
    private JTextField javaDir = new JTextField();
    private JButton jLabel11 = new JButton();
    private JTextField jspDir = new JTextField();
    private JLabel jLabel12 = new JLabel();
    private JTextField rootPackage = new JTextField();
    private GridLayout gridLayout3 = new GridLayout();
    private JCheckBox enableModel = new JCheckBox();
    private JCheckBox enableAction = new JCheckBox();
    private JCheckBox enableDao = new JCheckBox();
    private JCheckBox enableService = new JCheckBox();
    private JCheckBox enableWebservice = new JCheckBox();
    private JCheckBox enableHbm = new JCheckBox();
    private JCheckBox enableConfig = new JCheckBox();
    private JCheckBox enableMeta = new JCheckBox();
    private JCheckBox enableJsp = new JCheckBox();
    public DataPanel() {
        try {
            jbInit();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    private void jbInit() throws Exception {
        this.setLayout(borderLayout1);
        jLabel1.setText("数据库类型:");
        jPanel1.setLayout(gridLayout1);
        gridLayout1.setColumns(6);
        gridLayout1.setRows(2);
        tableParser.setToolTipText("");
        jLabel2.setText("说明:");
        jPanel2.setLayout(borderLayout2);
        jPanel3.setLayout(gridLayout2);
        jLabel3.setText("驱动程序:");
        gridLayout2.setColumns(6);
        gridLayout2.setRows(2);
        driver.setText("com.mysql.jdbc.Driver");
        jLabel4.setText("URL");
        url.setText("jdbc:mysql://localhost/information_schema");
        jLabel5.setText("用户名:");
        username.setText("root");
        jLabel6.setText("口令:");
        jLabel7.setText("数据库:");
        schema.setText("framework");
        jLabel8.setText("表名前缀:");
        tablePrefix.setText("t_");
        jLabel9.setText("子模块名:");
        submodule.setText("test");
        jLabel10.setText("Java源文件路径:");
        jLabel11.setText("JSP文件存放路径:");
        jspDir.setText("E:\\tmp");
        jLabel12.setText("根包名:");
        jPanel4.setLayout(gridLayout3);
        gridLayout3.setRows(2);
        enableModel.setSelected(true);
        enableModel.setText("是否输出业务对象");
        enableAction.setSelected(true);
        enableAction.setText("是否输出Struts Action");
        enableDao.setSelected(true);
        enableDao.setText("是否输出DAO");
        enableService.setSelected(true);
        enableService.setText("是否输出Service");
        enableWebservice.setSelected(true);
        enableWebservice.setText("是否输出Web Service");
        enableHbm.setSelected(true);
        enableHbm.setText("是否输出HBM");
        enableConfig.setSelected(true);
        enableConfig.setText("是否输出配置");
        enableMeta.setSelected(true);
        enableMeta.setText("是否输出元数据");
        enableJsp.setSelected(true);
        enableJsp.setText("是否输出JSP");
        rootPackage.setText("whf.framework.test");
        javaDir.setText("E:\\tmp");
        jPanel1.add(jLabel1);
        jPanel1.add(tableParser);
        jPanel1.add(jLabel9);
        jPanel1.add(submodule);
        jPanel1.add(jLabel12);
        jPanel1.add(rootPackage);
        jPanel1.add(jLabel10);
        jPanel1.add(javaDir);
        jPanel1.add(jLabel11);
        jPanel1.add(jspDir);
        jPanel1.add(jLabel2);
        jPanel1.add(description);
        this.add(jPanel2, java.awt.BorderLayout.CENTER);
        jPanel2.add(jPanel3, java.awt.BorderLayout.NORTH);
        jPanel3.add(jLabel3);
        jPanel3.add(driver);
        jPanel3.add(jLabel4);
        jPanel3.add(url);
        jPanel3.add(jLabel7);
        jPanel3.add(schema);
        jPanel3.add(jLabel5);
        jPanel3.add(username);
        jPanel3.add(jLabel6);
        jPanel3.add(password);
        jPanel3.add(jLabel8);
        jPanel3.add(tablePrefix);
        jPanel2.add(jPanel4, java.awt.BorderLayout.CENTER);
        jPanel4.add(enableModel);
        jPanel4.add(enableAction);
        jPanel4.add(enableDao);
        jPanel4.add(enableService);
        jPanel4.add(enableWebservice);
        jPanel4.add(enableHbm);
        jPanel4.add(enableConfig);
        jPanel4.add(enableMeta);
        jPanel4.add(enableJsp);
        //
        for(int i=0; i<DATABASE_TYPES.length; i++){
            this.tableParser.addItem(new SimpleObject(DATABASE_TYPES[i]));
        }
        this.tableParser.addItemListener(new ItemListener(){
        	public void itemStateChanged(ItemEvent event){
        		SimpleObject so = (SimpleObject)event.getItem();
        		driver.setText(so.driver);
        		url.setText(so.url);
        		username.setText(so.username);
        		password.setText(so.password);
        		
        		driver.setToolTipText(so.driver);
        		url.setToolTipText(so.url);
        		username.setToolTipText(so.username);
        		password.setToolTipText(so.password);
        		//
        		schema.setText(so.dbName);
        		javaDir.setText(so.javaDir);
        		jspDir.setText(so.jspDir);
        		submodule.setText(so.subModule);
        		tablePrefix.setText(so.tablePre);
        		rootPackage.setText(so.rootPackage);

        		schema.setToolTipText(so.dbName);
        		javaDir.setToolTipText(so.javaDir);
        		jspDir.setToolTipText(so.jspDir);
        		submodule.setToolTipText(so.subModule);
        		tablePrefix.setToolTipText(so.tablePre);
        		rootPackage.setToolTipText(so.rootPackage);
        	}
        });
        //
        this.add(jPanel1, java.awt.BorderLayout.NORTH);
        this.tableParser.setSelectedIndex(0);
        //
        this.jLabel10.addActionListener(new ActionListener(){
        	public void actionPerformed(ActionEvent e) {
        		JFileChooser fileChooser = new JFileChooser();
        		fileChooser.setDialogTitle("请选择Java文件的存放目录！");
        		fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
        		fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        		fileChooser.setCurrentDirectory(new File(javaDir.getText()));
				int result=fileChooser.showOpenDialog(null);  
				if(result==JFileChooser.APPROVE_OPTION){   
					File f = fileChooser.getSelectedFile();
					javaDir.setText(f.getAbsolutePath());
				} 
        	}
        });
        
        this.jLabel11.addActionListener(new ActionListener(){
        	public void actionPerformed(ActionEvent e) {
        		JFileChooser fileChooser = new JFileChooser();
        		fileChooser.setDialogTitle("请选择JSP文件的存放目录！");
        		fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
        		fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        		fileChooser.setCurrentDirectory(new File(jspDir.getText()));
				int result=fileChooser.showOpenDialog(null);  
				if(result==JFileChooser.APPROVE_OPTION){   
					File f = fileChooser.getSelectedFile();
					jspDir.setText(f.getAbsolutePath());
				} 
        	}
        });
    }

    private boolean isEmpty(String input){
        if(input == null || "".equals(input)){
            return true;
        } else {
            return false;
        }
    }

    public void checkValidation() throws ValidationException{
        if(tableParser.getSelectedIndex() == -1){
            throw new ValidationException("没有选择数据库类型!");
        }
        File f = null;
        if(isEmpty(javaDir.getText())){
            throw new ValidationException("Java存储路径不能空!");
        }
        f = new File(javaDir.getText());
        if(!f.exists()){
            throw new ValidationException("指定的Java存储路径不存在!");
        } else if(!f.isDirectory()){
            throw new ValidationException("指定的Java存储路径不是目录!");
        }
        if(isEmpty(jspDir.getText())){
            throw new ValidationException("Jsp存储路径不能空!");
        }
        f = new File(jspDir.getText());
        if(!f.exists()){
            throw new ValidationException("指定的Jsp存储路径不存在!");
        } else if(!f.isDirectory()){
            throw new ValidationException("指定的Jsp存储路径不是目录!");
        }
        if(isEmpty(driver.getText())){
            throw new ValidationException("驱动程序不能空!");
        }
        if(isEmpty(url.getText())){
            throw new ValidationException("url不能空!");
        }
        if(isEmpty(username.getText())){
            throw new ValidationException("用户名不能空!");
        }
    }
    
    public void loadFromConfig(Config cfg){
    	if(cfg == null) return;
    	driver.setText(cfg.getDriver());
    	url.setText(cfg.getUrl());
    	username.setText(cfg.getUsername());
    	password.setText(cfg.getPassword());
    	schema.setText(cfg.getSchema());
    	tablePrefix.setText(cfg.getTablePrefix());
    	
    	submodule.setText(cfg.getSubModule());
    	rootPackage.setText(cfg.getRootPackage());
    	javaDir.setText(cfg.getJavaDir());
    	jspDir.setText(cfg.getJspDir());
    	
    	for(int i=0; i< tableParser.getItemCount(); i++){
    		SimpleObject so = (SimpleObject)tableParser.getItemAt(i);
    		if(StringUtils.equalsIgnoreCase(so.value, cfg.getTableParser())){
    			tableParser.setSelectedIndex(i);
    			break;
    		}
    	}
    	
    	enableModel.setSelected(cfg.isEnableModel());
    	enableAction.setSelected(cfg.isEnableAction());
    	enableDao.setSelected(cfg.isEnableDao());
    	enableService.setSelected(cfg.isEnableService());
    	enableWebservice.setSelected(cfg.isEnableWebservice());
    	enableConfig.setSelected(cfg.isEnableConfig());
    	enableMeta.setSelected(cfg.isEnableMeta());
    	enableHbm.setSelected(cfg.isEnableHbm());
    	enableJsp.setSelected(cfg.isEnableJsp());
    }

    public Config getConfig(Config cfg){
        if(cfg == null) cfg = new Config();
        cfg.setDriver(driver.getText());
        cfg.setUrl(url.getText());
        cfg.setUsername(username.getText());
        cfg.setPassword(password.getText());
        cfg.setSchema(schema.getText());
        cfg.setTablePrefix(tablePrefix.getText());

        cfg.setSubModule(submodule.getText());
        cfg.setRootPackage(rootPackage.getText());
        cfg.setJavaDir(javaDir.getText());
        cfg.setJspDir(jspDir.getText());

        SimpleObject so = (SimpleObject)tableParser.getSelectedItem();
        if(so != null){
            cfg.setTableParser(so.value);
            cfg.setTablesSql(so.sql);
        }

        cfg.setEnableModel(enableModel.isSelected());
        cfg.setEnableAction(enableAction.isSelected());
        cfg.setEnableDao(enableDao.isSelected());
        cfg.setEnableDaoImp(enableDao.isSelected());
        cfg.setEnableService(enableService.isSelected());
        cfg.setEnableServiceImp(enableService.isSelected());
        cfg.setEnableWebservice(enableWebservice.isSelected());
        cfg.setEnableConfig(enableConfig.isSelected());
        cfg.setEnableMeta(enableMeta.isSelected());
        cfg.setEnableHbm(enableHbm.isSelected());
        cfg.setEnableJsp(enableJsp.isSelected());

        return cfg;
    }

    class SimpleObject{
        private String name;
        private String value;
        private String sql;
        private String driver;
        private String url;
        private String username;
        private String password;
        //
        private String dbName;
        private String javaDir;
        private String jspDir;
        private String subModule;
        private String tablePre;
        private String rootPackage;

        public SimpleObject(String[] params){
            this.name = 		params[0];
            this.value = 		params[1];
            this.sql = 			params[2];
            this.driver = 		params[3];
            this.url = 			params[4];
            this.username = 	params[5];
            this.password = 	params[6];

            this.dbName = 		params[7];
            this.javaDir =		params[8];
            this.jspDir = 		params[9];
            this.subModule = 	params[10];
            this.tablePre = 	params[11];
            this.rootPackage = 	params[12];
        }

        public String toString(){
            return name;
        }
    }
    
    public static void main(String[] args) throws Exception{
    	Class.forName("oracle.jdbc.driver.OracleDriver");
    	Connection con = DriverManager.getConnection("jdbc:oracle:thin:@192.168.20.8:1523:ora92", "wlrk_new","a");
    	con.close();
    }
}
